#include "Acceptor.h"
#include "EventLoop.h"
#include "Channel.h"

Acceptor::Acceptor(EventLoop *loop, const std::string &ip, uint16_t port)
{
    this->loop = loop;
    servSock.fd = CreateNonBlockSocket();
    servSock.ip = ip;
    servSock.port = port;
    SetReuseAddr(servSock.fd, 1);
    SetReusePort(servSock.fd, 1);
    SetKeepAlive(servSock.fd, 1);
    SetTcpNoDelay(servSock.fd, 1);
    Bind(servSock.fd, ip, port);
    Listen(servSock.fd);
    channel = std::make_unique<Channel>(this->loop, servSock.fd);
    channel->onRead = [this] { OnConnection(); };
    channel->EnableReading();
}

Acceptor::~Acceptor()
{
    SAFE_CLOSESOCKET(servSock.fd);
}

void Acceptor::OnConnection() const
{
    std::string clientIp;
    uint16_t clientPort;
    int clientFd = Accept(servSock.fd, clientIp, clientPort);
    Socket sock = {clientFd, clientIp, clientPort};
    onConnection(sock);
}